<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加奖学金申请</el-button>
    <el-table :data="applications" style="margin-top: 10px" border>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="year" label="年份" width="100" />
      <el-table-column prop="moralScore" label="思政分" width="100" />
      <el-table-column prop="academicScore" label="学业分" width="100" />
      <el-table-column prop="researchScore" label="科研分" width="100" />
      <el-table-column prop="serviceScore" label="服务分" width="100" />
      <el-table-column prop="totalScore" label="总分" width="100" />
      <el-table-column prop="result" label="结果" width="100" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="奖学金申请" @close="resetForm">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="年份" prop="year">
          <el-input-number v-model="formData.year" :min="2000" :max="2100" />
        </el-form-item>
        <el-form-item label="思政分" prop="moralScore">
          <el-input-number v-model="formData.moralScore" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="学业分" prop="academicScore">
          <el-input-number v-model="formData.academicScore" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="科研分" prop="researchScore">
          <el-input-number v-model="formData.researchScore" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="服务分" prop="serviceScore">
          <el-input-number v-model="formData.serviceScore" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input-number v-model="formData.totalScore" :min="0" :max="400" />
        </el-form-item>
        <el-form-item label="结果" prop="result">
          <el-select v-model="formData.result" placeholder="请选择">
            <el-option label="通过" value="通过" />
            <el-option label="未通过" value="未通过" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ScholarshipApplicationsModule',
  props: {
    studentId: { type: Number, required: true }
  },
  data() {
    return {
      applications: [],
      dialogVisible: false,
      formData: this.initFormData(),
      rules: {
        year: [
          { required: true, message: '请输入年份', trigger: 'blur' },
          { type: 'number', min: 2000, max: 2100, message: '年份需在2000-2100之间', trigger: 'change' }
        ],
        moralScore: [{ type: 'number', min: 0, max: 100, message: '思政分需在0-100之间', trigger: 'change' }],
        academicScore: [{ type: 'number', min: 0, max: 100, message: '学业分需在0-100之间', trigger: 'change' }],
        researchScore: [{ type: 'number', min: 0, max: 100, message: '科研分需在0-100之间', trigger: 'change' }],
        serviceScore: [{ type: 'number', min: 0, max: 100, message: '服务分需在0-100之间', trigger: 'change' }],
        totalScore: [{ type: 'number', min: 0, max: 400, message: '总分需在0-400之间', trigger: 'change' }],
        result: [{ required: true, message: '请选择结果', trigger: 'change' }]
      }
    }
  },
  watch: {
    studentId: {
      handler(newVal) {
        if (typeof newVal === 'number' && !isNaN(newVal)) {
          this.loadData()
        } else {
          this.applications = []
        }
      },
      immediate: true
    }
  },
  methods: {
    initFormData() {
      return {
        id: null,
        studentId: this.studentId,
        year: new Date().getFullYear(),
        moralScore: 0,
        academicScore: 0,
        researchScore: 0,
        serviceScore: 0,
        totalScore: 0,
        result: ''
      }
    },
    async loadData() {
      try {
        const res = await axios.get(`/api/scholarshipapplications/student/${this.studentId}`)
        this.applications = res.data || []
      } catch (e) {
        this.$message.error('加载奖学金申请失败')
        console.error('加载奖学金申请失败:', e)
      }
    },
    openAddDialog() {
      this.formData = this.initFormData()
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.formData = { ...row, studentId: this.studentId }
      this.dialogVisible = true
    },
    async submit() {
      try {
        this.formData.studentId = this.studentId
        const valid = await this.$refs.formRef.validate()
        if (!valid) return

        let res
        if (this.formData.id) {
          res = await axios.put('/api/scholarshipapplications', this.formData)
        } else {
          res = await axios.post('/api/scholarshipapplications', this.formData)
        }

        if (res.data.code === 200 || res.data > 0) {
          this.$message.success(this.formData.id ? '更新成功' : '添加成功')
          this.dialogVisible = false
          await this.loadData()
          this.$emit('save-success')
        } else {
          this.$message.error(res.data.message || (this.formData.id ? '更新失败' : '添加失败'))
        }
      } catch (e) {
        this.$message.error('提交失败')
        console.error('提交奖学金申请失败:', e)
      }
    },
    async handleDelete(id) {
      try {
        const res = await axios.delete(`/api/scholarshipapplications/${id}`)
        if (res.data.code === 200 || res.data > 0) {
          this.$message.success('删除成功')
          await this.loadData()
          this.$emit('save-success')
        } else {
          this.$message.error('删除失败')
        }
      } catch (e) {
        this.$message.error('删除失败')
        console.error('删除奖学金申请失败:', e)
      }
    },
    resetForm() {
      this.$refs.formRef?.resetFields()
      this.formData = this.initFormData()
    }
  }
}
</script>
